Vue Js Generate Random Sign: To create a random sign using Vue.js, you can use a method that generates a random number between 0 and 1 and returns either a positive or negative sign based on the number generated.In this tutorial we will learn how to Create Random sign using Vue Js and native javascript method.
How to Create random sign in Vue Js?
he generateRandomSign method generates a random number between 0 and 1 using the Math.random() function. If the generated number is greater than or equal to 0.5, the randomSign property is set to a positive sign (‘+’). Otherwise, it’s set to a negative sign (‘-‘).
By calling the generateRandomSign method in the mounted hook, the component will display a random sign when it’s first rendered.
Vue Js Generate Random Sign Example
<div id="app">
<div v-if="currentSign">Current Sign: {{ currentSign }}</div><br>
<button @click="generateSign">Generate New Sign</button>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
currentSign: null
};
},
methods: {
generateSign() {
const randomNumber = Math.random();
this.currentSign = randomNumber >= 0.5 ? '+' : '-';
}
}
});
app.mount('#app');
</script>